package com.hui.security.sys.service.impl;

import com.hui.security.sys.entity.Permission;
import com.hui.security.sys.exception.ExceptionEnum;
import com.hui.security.sys.exception.PermissionException;
import com.hui.security.sys.mapper.PermissionMapper;
import com.hui.security.sys.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * <b><code>PermissionServiceImpl</code></b>
 * <p/>
 * Description:
 * <p/>
 * <b>Creation Time:</b> 2019/1/5 0:27.
 *
 * @author HuWeihui
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 新增权限
     * @param permission
     * @return
     */
    @Override
    public Permission add(Permission permission) {
        //判断是否有重复的权限
        if (null != permissionMapper.selectByNameOrUrl(permission.getPermissionName(), permission.getResourceUrl())) {
            throw new PermissionException(ExceptionEnum.PERMISSION_ERROR_REPEAT_PERMISSION);
        }
        permissionMapper.insert(permission);
        return permission;
    }

    /**
     * 删除权限
     * @param permissionId
     */
    @Override
    public void delete(String permissionId) {
        permissionMapper.deleteByPrimaryKey(permissionId);
    }

    /**
     * 更新权限
     * @param permission
     */
    @Override
    public void update(Permission permission) {
        //判断是否有重复的权限
        if (null != permissionMapper.selectByNameOrUrl(permission.getPermissionName(), permission.getResourceUrl())) {
            throw new PermissionException(ExceptionEnum.PERMISSION_ERROR_REPEAT_PERMISSION);
        }
        permissionMapper.updateByPrimaryKey(permission);
    }

    /**
     * 获取权限信息
     * @param permissionId
     * @return
     */
    @Override
    public Permission get(String permissionId) {
        return permissionMapper.selectByPrimaryKey(permissionId);
    }

    /**
     * 查询用户相关权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<Permission> listByUserId(String userId) {
        return permissionMapper.selectByUserId(userId);
    }

    /**
     * 查询角色相关权限
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Permission> listByRoleId(String roleId) {
        return permissionMapper.selectByRoleId(roleId);
    }
}
